<?php
/**
 * add module
 */

function moduleIns(){
	global $objSDAO;
	$errMsg = "";
	if(ereg("[^a-z0-9]{4}",$_REQUEST["module"]))
		$errMsg .= _t("name : a-z 0-9 only").".<br>";
	if(trim($_REQUEST["description"]) == '')
		$errMsg .= _t("description missing")."<br>";
	//controllo che il modulo non esista gi@
	$sSQL = "SELECT count(*) as num FROM module WHERE module='".$_REQUEST["module"]."'";
	$num = 0;
	$objSDAO->query($sSQL,"test");
	$row = $objSDAO->fetch('test');
	if($row["num"] != 0) {
		$errMsg .= _t("existing name");
		return $errMsg;
	}
	$sSQL = "INSERT INTO " .
			"module " .
			"(module, " .
			"description, " .
			"note)" .
			"VALUES('".addslashes(sxGPC(strtolower($_REQUEST["module"])))."', " .
			"'".addslashes(sxGPC(trim($_REQUEST["description"])))."', " .
			"'".addslashes(sxGPC(trim($_REQUEST["note"])))."'" .
			")";	
	
	$objSDAO->query($sSQL,"ins");
	$module = addslashes(sxGPC(strtolower($_REQUEST["module"])));
	if(insertDoc($module, $errMsg)){
		$_SESSION[USEROBJ]->reLoad();
		$url = $_SESSION[USEROBJ]->getHistory(0, true);
		serverRedir($url);
	}else{
		$errMsg .= _t("document load failed");
	}
	return $errMsg;
}

/**
 * delete module
 */
function moduleDel(){
	global $objSDAO;
	$errMsg = "";
	if(!isset($_REQUEST["module"]) || $_REQUEST["module"] == "")
		$errMsg .= _t("module missing");
	$module = $_REQUEST["module"];
	//verifico che la data_area non sia usata
	$sSQL = "SELECT count(*) AS num FROM sub_module WHERE module='".$_REQUEST["module"]."'";
	$objSDAO->query($sSQL,"tst");
	$row = $objSDAO->fetch("tst");
	if($row["num"] >0){
		$errMsg .= _t("sub-modules existing")."<br>";
	}
	if ($errMsg!='') return $errMsg;
	
	//delete documents
	$sSQL = "SELECT * FROM module_doc WHERE module='$module'";
	$objSDAO->query($sSQL, "sel");
	while($row = $objSDAO->fetch("sel")){
		if(file_exists(SERVER_FS_DOC."/mb_module/$module/".$row["file_name"])){
			@unlink(SERVER_FS_DOC."/mb_module/$module/".$row["file_name"]);
		}
	}
	$sSQL = "DELETE FROM module_doc WHERE module='$module'";
	$objSDAO->query($sSQL, "del");
	//delete docs folder
	rmdir(SERVER_FS_DOC."/mb_module/$module");
	$sSQL = "DELETE FROM functional_area " .
			"WHERE module='".$_REQUEST["module"]."'";	
	$objSDAO->query($sSQL,"del");
	$sSQL = "DELETE FROM module " .
			"WHERE module='".$_REQUEST["module"]."'";	
	$objSDAO->query($sSQL,"del");
	$url = $_SESSION[USEROBJ]->getHistory(-1, true);
	serverRedir($url);
	return $errMsg;
}

/**
 * Modify module
 */
function moduleMod(){
	global $objSDAO;
	$errMsg = "";
	if(trim($_REQUEST["description"]) == "")
		$errMsg .= _t("description missing")."<br>";
	if($errMsg == ""){
		$sSQL = "UPDATE module " .
				"SET description='".addslashes(sxGPC(trim($_REQUEST["description"])))."', " .
				"note='".addslashes(sxGPC(trim($_REQUEST["note"])))."'" .
				"WHERE module='".addslashes(sxGPC($_REQUEST["module"]))."'";	
		$objSDAO->query($sSQL, "mod");
		$module = addslashes(sxGPC(strtolower($_REQUEST["module"])));
		if(deleteDoc($module, $errMsg) && insertDoc($module, $errMsg)){
			$_SESSION[USEROBJ]->reLoad();
			$url = $_SESSION[USEROBJ]->getHistory(0, true);
			serverRedir($url);
		}else{
			$errMsg .= _t("document load failed");
		}
	}
	return $errMsg;
}

/**
 * 
 * document load 
 * 
 */
function insertDoc($module, &$errMsg) {
	global $objSDAO;
	$errMsg = "";
	$fileName = "";
	$name = "";
	if($_FILES["document"]["error"] == 0 && $_FILES["document"]["size"] != 0){ 
		$fileName = elabFileName($_FILES["document"]["name"]);
		$name = addslashes(sxGPC(trim($_REQUEST["doc_name"])));
		if($name == "") {
			$name = $fileName;
		}
		$sSQL = "SELECT count(*) AS numDoc FROM module_doc 
				WHERE module='$module' AND file_name='$fileName'";
		$objSDAO->query($sSQL, "count");
		$rowCount=$objSDAO->fetch("count");
		if($rowCount && $rowCount["numDoc"] == 0){
			$tmpFile = $_FILES["document"]["tmp_name"];
			if(!file_exists(SERVER_FS_DOC)){
				$errMsg .= _t("doc. folder '%s' not found",SERVER_FS_DOC)."<br>";
				return false;
			}
			if(!file_exists(SERVER_FS_DOC."/mb_module")){
				mkdir(SERVER_FS_DOC."/mb_module",0775);
			}
			if(!file_exists(SERVER_FS_DOC."/mb_module/$module")){
				mkdir(SERVER_FS_DOC."/mb_module/$module",0775);
			}
			if(!copy($tmpFile, SERVER_FS_DOC."/mb_module/$module/$fileName")){
				$errMsg .= _t("document write failed")."<br>";
				return false;
			}
			
			$sSQL = "INSERT INTO module_doc 
					(module, file_name, name, mime_type)
					VALUES
					('".addslashes(sxGPC(trim($module)))."', '$fileName', '$name', '".$_FILES["document"]["type"]."')";
			$objSDAO->query($sSQL,"upd");
		}
	}
	return true;
}

/**
 * add sub-module
 */

function subModIns(){
	global $objSDAO;
	$errMsg = "";
	if(ereg("[^a-z0-9]{4}",$_REQUEST["module"]))
		$errMsg .= _t("module name : a-z 0-9 only").".<br>";
	if(ereg("[^a-z0-9]{4}",$_REQUEST["sub_module"]))
		$errMsg .= _t("sub-module name : a-z 0-9 only").".<br>";
	if(trim($_REQUEST["description"]) == '')
		$errMsg .= _t("description missing")."<br>";
	$sSQL = "SELECT count(*) as num FROM sub_module WHERE module='".$_REQUEST["module"]."' AND sub_module='".$_REQUEST["sub_module"]."'";
	$num = 0;
	if($objSDAO->query($sSQL,"test",array("contOnErr"=>true))){
		if($row = $objSDAO->fetch("test")){
			$num = $row["num"]; 
		}
	}else{
		$errMsg .= $objSDAO->error;
	}
	if($num != 0)
		$errMsg .= _t("sub-module existing");
	$errMsg .= moduleCheck();
	
	if($errMsg == ""){		
		$sSQL = "INSERT INTO " .
				"sub_module " .
				"(module, functional_area, sub_module, description, note)" .
				"VALUES('".addslashes(sxGPC(strtolower($_REQUEST["module"])))."', " .
				"'".addslashes(sxGPC(trim($_REQUEST["functional_area"])))."', " .
				"'".addslashes(sxGPC(trim($_REQUEST["sub_module"])))."', " .
				"'".addslashes(sxGPC(trim($_REQUEST["description"])))."', " .
				"'".addslashes(sxGPC(trim($_REQUEST["note"])))."'" .
				")";	
		
		if($objSDAO->query($sSQL,"ins",array("contOnErr"=>true))){
			$module = addslashes(sxGPC(strtolower($_REQUEST["module"])));
			$subModule = addslashes(sxGPC(strtolower($_REQUEST["sub_module"])));
			$url = $_SESSION[USEROBJ]->getHistory(0, true);
			serverRedir($url);
		}else{
			$errMsg .= $sSQL."<br> - ".$objSDAO->error;
		}
	}
	return $errMsg;
}


/**
 * Modify sub-module
 */
function subModMod() {
	global $objSDAO;
	$errMsg = "";
	if(trim($_REQUEST["description"]) == "")
		$errMsg .= _t("missing description")."<br>";
	$errMsg .= moduleCheck();
	$_REQUEST['new_sub_module'] = strtolower(trim($_REQUEST['new_sub_module']));
	if (ereg("[^a-z0-9_]",sxREQUEST('new_sub_module'))) {
		$errMsg .= _t("sub-module name : a-z 0-9 _ only")."<br>";
	}
	if($errMsg != ""){return $errMsg;}

	if (sxREQUEST('new_sub_module') != sxREQUEST('sub_module')) {
		$sSQL = "SELECT count(*) AS num FROM process_unit " .
				" WHERE (module='".sxRAS("module")."' AND sub_module='".sxRAS("sub_module")."') " .
						" OR process_unit LIKE '".sxRAS("module").".".sxRAS("sub_module")."%'";	
		$objSDAO->query($sSQL, "test");
		$row = $objSDAO->fetch('test');
		if ($row['num'] != 0) {
			$errMsg .= _t("process exiswting - no delete")."<br>";
		}
		$sSQL = "SELECT count(*) AS num FROM sub_module " .
				" WHERE module='".sxRAS("module")."' " .
						" AND sub_module='".sxRAS("new_sub_module")."'";	
		$objSDAO->query($sSQL, "test");
		$row = $objSDAO->fetch('test');
		if ($row['num'] != 0) {
			$errMsg .= _t("sub-module existing")."<br>";
		}
	}
	
	if($errMsg != ""){return $errMsg;}
	$sSQL = "UPDATE sub_module SET " .
			" functional_area='".sxRAS("functional_area")."', " .
			" description='".trim(sxRAS("description"))."', " .
			" note='".trim(sxRAS("note"))."'" .
			" WHERE module='".sxRAS("module")."' " .
					" AND sub_module='".sxRAS("sub_module")."'";	
	$objSDAO->exec($sSQL);

	if (sxREQUEST('new_sub_module') != sxREQUEST('sub_module')) {
		$sSQL = "UPDATE sub_module SET sub_module='".sxRAS("new_sub_module")."'" .
				" WHERE module='".sxRAS("module")."' " .
						" AND sub_module='".sxRAS("sub_module")."'";	
		$objSDAO->exec($sSQL);
	}
	
	$url = $_SESSION[USEROBJ]->getHistory(0, true);
	serverRedir($url);
}

function moduleCheck() {
	global $objSDAO;
	$errMsg = "";
	$sSQL = "SELECT * FROM module WHERE module='".addslashes(sxGPC($_REQUEST["module"]))."'";
	if($objSDAO->query($sSQL, "mod", array("contOnErr"=>true))){
		if($row = $objSDAO->fetch("mod")){
			return "";
		}else{
			$errMsg .= _t("existing module");
			return $errMsg;
		}
	}else{
		$errMsg .= $sSQL."<br> - ".$objSDAO->error;
		return $errMsg;
	}
		
}

/**
 * ripulisce il fileName originale
 */
 function elabFileName($nomeFile) {
 		$elabFileName = ereg_replace('[^a-zA-Z 0-9 . - _]', "_", str_replace(" ", "_", $nomeFile));
 		return $elabFileName;
 }
 
 /**
  * elimina gli allegati del modulo
  */
 function deleteDoc($module, &$errMsg) {
 	global $objSDAO;
	$errMsg = "";
	$fileName = "";
	$name = "";
	foreach($_REQUEST as $key=>$value){
		if(strpos($key, "elim_") !== false && strtolower($value) == "on"){
			$fileName = $_REQUEST["fn_$key"];
			if(file_exists(SERVER_FS_DOC."/mb_module/$module/$fileName")){
				unlink(SERVER_FS_DOC."/mb_module/$module/$fileName");
			}
			$sSQL = "DELETE FROM module_doc WHERE module='$module' AND file_name='$fileName'";
			$objSDAO->query($sSQL, "del");
		}
	}
	return true;
 }
